<?php
declare(strict_types=1);

namespace App\Controller;


use App\Model\User;

/**
 * Class WeChatController
 * @package App\Controller
 */
class WeChatController extends AbstractWeChatController
{

    protected $user;

    public function __construct()
    {
        parent::__construct();
    }

    public function register()
    {
        $code = $this->request->input('code');
        $data = [];
        if ($code) {
            $wechat_info =  $this->forMiniApp()->getInfo($code);
            $openid = $wechat_info['openid'];
            if (empty($openid)) throw new \Exception('openid获取失败！');
            $data['openid'] = $openid;
        }
        $data['username'] = $this->request->input('username');
        if (User::getUserByUsername($data['username'])) {
            throw new \Exception("用户名已存在！");
        }
        $data['password'] = sha1($this->request->input('password'));
        return User::query()->create($data);
    }

    public function login() {
        $username = $this->request->input('username');
        $password = $this->request->input('password');
        $user = User::getUserByUsername($username, sha1($password));
        if (!$user) throw new \Exception("账号或密码错误！");
        $user['token'] = sha1($user['uid'].env('WeChatToken').time());
        cache()->set('sybd_token_'.$user['token'], $user, 86400);
        return $user;
    }
}